<template>
  <div style="display: flex; justify-content: space-between">
    <a-form size="small" :model="pageData" layout="inline" style="margin-bottom: 10px">
      <a-form-item label="计划时间">
        <a-month-picker
          popup-container="html"
          class="bacClass"
          v-model="pageData.planMonth"
          style="width: 200px"
        />
      </a-form-item>
      <a-form-item label="检查单号">
        <a-input
          class="bacClass"
          style="width: 200px"
          v-model="pageData.planCode"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item label="检查名称">
        <a-input
          class="bacClass"
          style="width: 200px"
          v-model="pageData.planName"
          allow-clear
        ></a-input>
      </a-form-item>
      <a-form-item
        v-if="tabKey == 3"
        label="状态"
        field="status"
        :rules="[{ required: true, message: '状态必填' }]"
        :validate-trigger="['change', 'blur']"
      >
        <a-select class="bacClass" style="width: 200px" v-model="pageData.status">
          <a-option :value="4">已审核</a-option>
          <a-option :value="3">待审核</a-option>
          <a-option value="null">全部</a-option>
        </a-select>
      </a-form-item>
    </a-form>
    <Toolbar
      :items="toolbarList"
      @select="selectHandle"
      @add="addHandle"
      @del="deleteHandle"
      @audit="auditHandle()"
      @counter="auditHandle()"
    >
    </Toolbar>
  </div>
  <div class="cssTable">
    <a-tabs :lazy-load="true" :justify="true" default-active-key="1" @change="tabChange">
      <a-tab-pane title="未审核" key="1">
        <a-spin
          :loading="pageData.pageLoading"
          tip="加载中"
          dot
          style="height: 100%; width: 98.5%; z-index: 999; margin-left: 13px"
        >
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            :style="{ height: pageData.rHeight - 200 + 'px' }"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReady"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.tableList"
            :columnDefs="tableColumns"
            :localeText="localeText1"
          ></AgGridVuesCopys>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane title="计划已审核" key="2">
        <a-spin
          :loading="pageData.pageLoading"
          tip="加载中"
          dot
          style="height: 100%; width: 98.5%; z-index: 999; margin-left: 13px"
        >
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            :style="{ height: pageData.rHeight - 200 + 'px' }"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReadyJH"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.tableList"
            :columnDefs="tableColumnsJH"
            :localeText="localeText1"
          ></AgGridVuesCopys>
        </a-spin>
      </a-tab-pane>
      <a-tab-pane title="结果审核" key="3">
        <a-spin
          :loading="pageData.pageLoading"
          tip="加载中"
          dot
          style="height: 100%; width: 98.5%; z-index: 999; margin-left: 13px"
        >
          <AgGridVuesCopys
            :rowHeight="33"
            :headerHeight="33"
            :suppressCopyRowsToClipboard="true"
            :style="{ height: pageData.rHeight - 200 + 'px' }"
            :suppressDragLeaveHidesColumns="true"
            rowSelection="multiple"
            @grid-ready="gridReadyJG"
            :defaultColDef="defaultColDef"
            class="ag-theme-alpine"
            :rowData="pageData.tableList"
            :columnDefs="tableColumnsJH"
            :localeText="localeText1"
          ></AgGridVuesCopys>
        </a-spin>
      </a-tab-pane>
    </a-tabs>
  </div>
  <paginationCopys
    :page-size-options="pagingList1"
    :total="total"
    show-total
    show-jumper
    show-page-size
    @change="PageSize"
    @page-size-change="change1"
    style="justify-content: center; margin-top: 12px"
    :page-size="size"
    :current="page"
  />
  <a-drawer
    style="z-index: 999"
    ok-text="保存"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    popup-container=".arco-tabs-content"
    height="100%"
    placement="bottom"
    :mask-closable="false"
    :visible="pageData.showAdd"
    unmountOnClose
    @ok="sideOk"
    @cancel="sideNo"
  >
    <template #title>
      {{ pageData.sideTitle }}
    </template>
    <div>
      <a-form ref="formRef" layout="inline" :model="dataForm">
        <a-form-item
          label="检查时间"
          field="planName"
          :rules="[{ required: true, message: '检查时间必填' }]"
          :validate-trigger="['change', 'blur']"
        >
          <a-month-picker
            class="bacClass"
            v-model="dataForm.planMonth"
            @change="changeName"
            style="width: 120px"
            :disabled="pageData.isDetail || pageData.sideTitle == '修改内审计划'"
          />
          <a-select
            class="bacClass"
            v-model="dataForm.planPeriod"
            @change="changeName"
            style="width: 90px; margin-left: -2px; height: 32px"
            :disabled="pageData.isDetail || pageData.sideTitle == '修改内审计划'"
          >
            <a-option value="上半月">上半月</a-option>
            <a-option value="下半月">下半月</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="检查名称"
          field="planName"
          :rules="[{ required: true, message: '检查名称必填' }]"
          :validate-trigger="['change', 'blur']"
        >
          <a-input
            class="bacClass"
            v-model="dataForm.planName"
            style="width: 200px"
            disabled
          ></a-input>
        </a-form-item>
      </a-form>
      <AgGridVuesCopys
        v-if="tabKey == 1"
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReadyGR"
        style="height: 175px; margin-top: 20px"
        :defaultColDef="defaultColDef2"
        class="ag-theme-alpine"
        :rowData="pageData.planOperatorList"
        :columnDefs="tableColumnsGR"
        :localeText="localeText1"
      ></AgGridVuesCopys>
      <a-space style="margin-top: 20px">
        <Toolbar
          v-if="!pageData.isDetail"
          :items="['新增检查内容', '删除']"
          @selectSOP="selectSOPcheck"
          @del="deleteSOPcheck"
        ></Toolbar>
      </a-space>
      <AgGridVuesCopys
        v-if="tabKey != 3"
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady2"
        style="height: 395px"
        :defaultColDef="defaultColDef2"
        class="ag-theme-alpine"
        :rowData="pageData.addList"
        :columnDefs="tableColumns2"
        :localeText="localeText1"
      ></AgGridVuesCopys>
      <AgGridVuesCopys
        v-if="tabKey == 3"
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        rowSelection="multiple"
        @grid-ready="gridReady4"
        style="height: 395px"
        :defaultColDef="defaultColDef2"
        class="ag-theme-alpine"
        :rowData="pageData.addList"
        :columnDefs="tableColumns4"
        :localeText="localeText1"
      ></AgGridVuesCopys>
    </div>
    <template #footer>
      <a-button @click="sideNo">关闭</a-button>
      <a-button type="primary" @click="sideOk" v-if="!pageData.isDetail">保存</a-button>
    </template>
  </a-drawer>

  <!-- 汇总/个人检查明细 -->
  <a-drawer
    style="z-index: 999"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    popup-container=".arco-tabs-content"
    height="100%"
    placement="bottom"
    :mask-closable="false"
    :visible="pageData.detialShow"
    unmountOnClose
    @cancel="pageData.detialShow = false"
  >
    <template #title>汇总/个人检查明细</template>
    <ag-grid-vue
      :rowHeight="33"
      :headerHeight="33"
      :suppressCopyRowsToClipboard="true"
      :suppressDragLeaveHidesColumns="true"
      rowSelection="multiple"
      @grid-ready="gridReady4"
      style="height: 170px"
      :defaultColDef="defaultColDef2"
      class="ag-theme-alpine"
      :rowData="pageData.statList"
      :columnDefs="tableColumns5"
      :localeText="localeText1"
      :suppressRowTransform="true"
    ></ag-grid-vue>
    <AgGridVuesCopys
      :rowHeight="33"
      :headerHeight="33"
      :suppressCopyRowsToClipboard="true"
      :suppressDragLeaveHidesColumns="true"
      rowSelection="multiple"
      @grid-ready="gridReady4"
      style="height: 470px; margin-top: 20px"
      :defaultColDef="defaultColDef2"
      class="ag-theme-alpine"
      :rowData="pageData.resultList"
      :columnDefs="tableColumns6"
      :localeText="localeText1"
      :suppressRowTransform="true"
    ></AgGridVuesCopys>
    <template #footer>
      <a-button @click="pageData.detialShow = false">关闭</a-button>
    </template>
  </a-drawer>

  <!-- 选择SOP内审检查项 -->
  <a-modal
    fullscreen
    v-model:visible="pageData.checkVisible"
    :on-before-ok="handleOk"
    @cancel="pageData.checkVisible = false"
    :mask-closable="false"
  >
    <template #title> 选择SOP内审检查项</template>
    <div style="width: 100%; display: flex; justify-content: space-between">
      <a-form-item label="检查内容">
        <a-input
          class="bacClass"
          style="width: 200px"
          v-model="pageData.inspectContent"
          allow-clear
        ></a-input>
      </a-form-item>
      <Toolbar :items="['查询']" @select="QuerySOPchecks()"></Toolbar>
    </div>
    <AgGridVuesCopys
      :rowHeight="33"
      :headerHeight="33"
      :suppressCopyRowsToClipboard="true"
      :suppressDragLeaveHidesColumns="true"
      rowSelection="multiple"
      @grid-ready="gridReady3"
      style="height: 650px"
      :defaultColDef="defaultColDef"
      class="ag-theme-alpine"
      :rowData="pageData.checkList"
      :columnDefs="tableColumns3"
      :localeText="localeText1"
    ></AgGridVuesCopys>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize3"
      @page-size-change="change3"
      style="justify-content: center; margin-top: 12px"
      :page-size="size"
      :current="page"
    />
  </a-modal>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, Ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
  pageLoading: false,
  showAdd: false,
  checkVisible: false,
  sideTitle: '',
  rHeight: 0,
  tableList: [],
  addList: [],
  checkList: [],
  machineList: [],
  operatorList: [],
  planOperatorList: [],
  isDetail: false,
  inspectName: '',
  inspectContent: '',
  planCode: '',
  planName: '',
  status: 0, // 0未审核 1已审核 2进行中 3计划完成 4结果完成
  planType: 0,
  statusGroup: '',
  content: '',
  isChecked: false,
  detialShow: false,
  statList: [],
  resultList: [],
})

const dataForm: any = reactive({
  planName: '',
  planMonth: '',
  planPeriod: '',
  id: null,
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}
//未审核
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}
const tableColumns: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  {
    headerName: '检查单号',
    field: 'planCode',
    width: 257,
  },
  {
    headerName: '检查名称',
    field: 'planName',
    width: 257,
  },
  {
    headerName: '计划月份',
    field: 'planMonth',
    width: 257,
  },
  {
    headerName: '创建人',
    field: 'createUser',
    width: 257,
  },
  {
    headerName: '创建时间',
    field: 'createTime',
    width: 257,
  },
  {
    headerName: '状态',
    field: 'status',
    pinned: 'right',
    width: 155,
    cellRenderer: {
      template: `<a-space>
                <el-tag type="warning" v-if="val.status == 0 ">待审核</el-tag>
                <el-tag type="warning" v-if="val.status == 3 ">待审核</el-tag>
                <el-tag type="success" v-if="val.status == 1 || val.status == 4 ">已审核</el-tag>
            </a-space>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '0' ? '待审核' : params.value == '3' ? '待审核' : '已审核'
      },
    },
  },
  {
    headerName: '操作',
    field: 'action',
    width: 160,
    pinned: 'right',
    cellRenderer: {
      template: `<a-space>
                           <a-tag class="tagCss" @click="c1" v-if="val.status == 0">修改</a-tag>
                           <a-tag class="tagCss" @click="c2">详情</a-tag>
                        </a-space>`,
      setup(props: any) {
        let val = ref(props.params.data)
        const c1 = () => {
          editHanler(props.params.data)
        }
        const c2 = () => {
          detail(props.params.data)
        }
        return {
          val,
          c1,
          c2,
        }
      },
    },
  },
]

//计划已审核
const gridOptionJH = ref()
const colStateJH = ref()
const gridReadyJH = (params: any) => {
  gridOptionJH.value = params.api
  colStateJH.value = params.columnApi
}

//结果已审核
const gridOptionJG = ref()
const colStateJG = ref()
const gridReadyJG = (params: any) => {
  gridOptionJG.value = params.api
  colStateJG.value = params.columnApi
}
const tableColumnsJH: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  {
    headerName: '检查单号',
    field: 'planCode',
    width: 185,
  },
  {
    headerName: '检查名称',
    field: 'planName',
    width: 185,
  },
  {
    headerName: '计划月份',
    field: 'planMonth',
    width: 185,
  },
  {
    headerName: '公司',
    field: 'companyNames',
    width: 185,
  },
  {
    headerName: '审核员',
    field: 'planOperator',
    width: 185,
  },
  {
    headerName: '创建人',
    field: 'createUser',
    width: 185,
  },
  {
    headerName: '创建时间',
    field: 'createTime',
    width: 186,
  },
  {
    headerName: '状态',
    field: 'status',
    pinned: 'right',
    width: 155,
    cellRenderer: {
      template: `<a-space>
              <el-tag type="success" v-if="val.status == 1">未开始</el-tag>
              <el-tag type="error" v-if="val.status == 2">进行中</el-tag>
              <el-tag type="warning" v-if="val.status == 3 ">待审核</el-tag>
              <el-tag type="success" v-if="val.status == 4 ">已审核</el-tag>
            </a-space>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == '1'
          ? '未开始'
          : params.value == '2'
          ? '进行中'
          : params.value == '3'
          ? '待审核'
          : '已审核'
      },
    },
  },
  {
    headerName: '操作',
    field: 'action',
    width: 150,
    pinned: 'right',
    cellRenderer: {
      template: `<a-space>
                           <a-tag class="tagCss" v-if="val.status == 1 ||  val.status == 4" @click="c1">反审</a-tag>
                           <a-tag class="tagCss" v-if="val.status == 2 || val.status == 3" disabled style="color:#d1d1d1 !important">反审</a-tag>
                           <a-tag class="tagCss" @click="c2">详情</a-tag>
                        </a-space>`,
      setup(props: any) {
        let val = ref(props.params.data)
        const c1 = () => {
          unAuditHandle(props.params.data)
        }
        const c2 = () => {
          detail(props.params.data)
        }
        return {
          val,
          c1,
          c2,
          tabKey,
        }
      },
    },
  },
]

//结果已审核
const defaultColDef2: any = {
  sortable: true,
  resizable: true,
  filter: true,
  flex: 1,
}
const gridOptionGR = ref()
const gridReadyGR = (params: any) => {
  gridOptionGR.value = params.api
}
const tableColumnsGR: any = [
  {
    headerName: '公司',
    field: 'companyName',
  },
  {
    headerName: '审核员',
    field: 'inspectorCodes',
    cellRenderer: {
      template: `<a-select popup-container="html" class="bacClass" v-model="val.inspectorCodes" multiple allow-clear
                        @focus="getPerson()" @change="c" :max-tag-count="10" :filter-option="false" v-if="!pageData.isDetail">
                            <a-option v-for="(item, index) in pageData.operatorList" :value="item.employeeCode"
                                :label="item.employeeName" :key="index">
                                {{ item.employeeCode + '/' + item.employeeName }}
                            </a-option>
                      </a-select>
                      <span v-if="pageData.isDetail">{{val.inspectorNames.join()}}</span>`,
      setup(props: any) {
        let val = ref(props.params.data)
        const c = () => {
          personChange(props.params.data)
        }
        return {
          c,
          val,
          pageData,
          getPerson,
          // personChange,
        }
      },
    },
  },
]

//分页
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}

//查询
function doRefresh() {
  pageData.pageLoading = true
  if (tabKey.value == 1) {
    pageData.status = 0
    pageData.statusGroup = ''
    pageData.planType = 0
  } else if (tabKey.value == 2) {
    pageData.status = null
    pageData.statusGroup = '1,2'
    pageData.planType = 1
  } else if (tabKey.value == 3) {
    pageData.statusGroup = '3,4'
    pageData.planType = 1
  }
  post({
    url: '/qms/inspectionPlan/pagedInspectionPlans',
    data: {
      current: page.value,
      size: size.value,
      planCode: pageData.planCode,
      planMonth: pageData.planMonth,
      planName: pageData.planName,
      status: pageData.status,
      statusGroup: pageData.statusGroup,
      planType: pageData.planType,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        pageData.tableList = data.records
        gridOption.value.setRowData(data.records)
        total.value = data.total
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const selectHandle = () => {
  page.value = 1
  doRefresh()
}

let tabKey = ref(1)
const toolbarList: any = ref(['查询', '新增', '删除', '审核'])
const tabChange = (e: any) => {
  tabKey.value = e
  if (e == 1) {
    toolbarList.value = ['查询', '新增', '删除', '审核']
  } else if (e == 2) {
    toolbarList.value = ['查询']
  } else if (e == 3) {
    toolbarList.value = ['查询', '审核']
    pageData.status = 3
  }
  doRefresh()
}

//详情
const detail = (record: any) => {
  get({
    url: '/qms/inspectionPlan/getInspectionPlan?id=' + record.id,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      dataForm.planName = data.planName
      dataForm.planMonth = data.planMonth
      dataForm.planPeriod = data.planPeriod
      pageData.addList = data.planDetailList
      data.planOperatorList.forEach((o: any) => {
        o.inspectorNames = o.inspectorNames.split(',')
        o.inspectorCodes = o.inspectorCodes.split(',')
      })
      getPerson()
      dataForm.companyIds = record.companyIds
      pageData.isDetail = true
      pageData.planOperatorList = data.planOperatorList
      pageData.showAdd = true
      pageData.sideTitle = '详情'
    }
  })
}

//新增
const addHandle = () => {
  if (dataForm.id) {
    delete dataForm.id
  }
  for (let item in dataForm) {
    dataForm[item] = ''
  }
  pageData.addList = []
  pageData.checkList = []
  getTreeCompany()
  pageData.showAdd = true
  pageData.sideTitle = '新增内审计划'
}
//修改
const editHanler = (record: any) => {
  get({
    url: '/qms/inspectionPlan/getInspectionPlan?id=' + record.id,
  }).then(({ data, code }: any) => {
    if (code === 200) {
      dataForm.planName = data.planName
      dataForm.planMonth = data.planMonth
      dataForm.planPeriod = data.planPeriod
      pageData.addList = data.planDetailList
      data.planOperatorList.forEach((o: any) => {
        o.inspectorNames = o.inspectorNames.split(',')
        o.inspectorCodes = o.inspectorCodes.split(',')
      })
      getPerson()
      getTreeCompany()
      pageData.planOperatorList.forEach((o1: any) => {
        let istrue = data.planOperatorList.find((o: any) => o.companyId === o1.companyId)
        if (istrue) {
          o1.inspectorNames = istrue.inspectorNames
          o1.inspectorCodes = istrue.inspectorCodes
        }
      })
      dataForm.id = record.id
      pageData.showAdd = true
      pageData.sideTitle = '修改内审计划'
    }
  })
}

//新增修改保存
const formRef = ref()
const sideOk = () => {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      if (pageData.addList.length === 0) {
        Message.warning('请选择检查内容！')
        return
      }
      if (pageData.planOperatorList.find((o: any) => !o.inspectorCodes)) {
        Message.warning('请填写所有公司的审核员！')
        return
      }
      pageData.addList.forEach((o: any) => {
        if (!o.planId) {
          o.planId = dataForm.id
        }
      })
      let list = JSON.parse(JSON.stringify(pageData.planOperatorList))
      list.forEach((o: any) => {
        if (o.inspectorCodes && Array.isArray(o.inspectorCodes)) {
          o.inspectorCodes = o.inspectorCodes.join(',')
          o.inspectorNames = o.inspectorNames.join(',')
        }
        if (!o.planId) {
          o.planId = dataForm.id
        }
      })
      post({
        url: '/qms/inspectionPlan/saveOrUpdateInspectionTemplate',
        data: {
          ...dataForm,
          planDetailList: pageData.addList,
          planOperatorList: list,
        },
      }).then(({ code, message }) => {
        if (code == 200) {
          Message.success('成功')
          pageData.showAdd = false
          doRefresh()
        } else {
          Message.error(message)
        }
      })
    }
  })
}

const sideNo = () => {
  pageData.showAdd = false
  pageData.isDetail = false
}

//删除
const deleteHandle = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请勾选数据')
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk: () => {
      post({
        url: '/qms/inspectionPlan/delInspectionPlans',
        data: gridOption.value.getSelectedRows().map((res: any) => res.id),
      }).then((res: any) => {
        if (res.code == 200) {
          Message.success('删除成功')
          doRefresh()
        } else {
          Message.error(res.message)
        }
      })
    },
  })
}

//审核
const auditHandle = () => {
  let data: any = []
  let auditUrl = ''
  if (tabKey.value == 1) {
    if (gridOption.value.getSelectedRows().length === 0) {
      Message.error('请勾选数据')
      return
    }
    data = gridOption.value.getSelectedRows().map((res: any) => {
      res.status = 1
      return {
        ...res,
      }
    })
    auditUrl = '/qms/inspectionPlan/auditInspectionTemplates'
  } else if (tabKey.value == 3) {
    if (gridOptionJG.value.getSelectedRows().length === 0) {
      Message.error('请勾选数据')
      return
    }
    data = gridOptionJG.value.getSelectedRows().map((res: any) => {
      return {
        id: res.id,
        status: 4,
      }
    })
    auditUrl = '/qms/inspectionPlan/auditInspectionResult'
  }

  Modal.confirm({
    title: '系统提示',
    content: '是否审核此单号?',
    onOk: () => {
      post({
        url: auditUrl,
        data: data,
      }).then((res: any) => {
        if (res.code == 200) {
          Message.success('成功！')
          doRefresh()
        } else {
          Message.error(res.message)
        }
      })
    },
  })
}

//反审
const unAuditHandle = (record: any) => {
  if (tabKey.value == 2) {
    Modal.confirm({
      title: '系统提示',
      content: '是否反审此单号?',
      onOk: () => {
        post({
          url: '/qms/inspectionPlan/unAuditInspectionPlan',
          data: {
            status: 0,
            planCode: record.planCode,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功！')
            doRefresh()
          } else {
            Message.error(res.message)
          }
        })
      },
    })
  } else if (tabKey.value == 3) {
    Modal.confirm({
      title: '系统提示',
      content: '是否反审此单号?',
      onOk: () => {
        post({
          url: '/qms/inspectionPlan/auditInspectionResult',
          data: [
            {
              id: record.id,
              status: 3,
            },
          ],
        }).then((res: any) => {
          if (res.code == 200) {
            Message.success('成功！')
            doRefresh()
          } else {
            Message.error(res.message)
          }
        })
      },
    })
  }
}

//新增表单
const gridOption2 = ref()
const colState2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
  colState2.value = params.columnApi
}
const tableColumns2: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  { headerName: '编号', field: 'itemId', width: 315 },
  { headerName: '检查内容', field: 'inspectContent', width: 320 },
  { headerName: '要求次数', field: 'inspectNumber', width: 320 },
  {
    headerName: '目标合格率',
    field: 'qualifiedRate',
    width: 320,
    cellRenderer: {
      template: `<span>{{ val.qualifiedRate + '%' }}</span>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '岗位', field: 'operatorPosition', width: 320 },
]

//选择检查内容
const selectSOPcheck = () => {
  pageData.checkVisible = true
  pageData.inspectName = ''
  pageData.inspectContent = ''
  QuerySOPchecks()
}

//删除
const deleteSOPcheck = () => {
  if (gridOption2.value.getSelectedRows().length == 0) {
    Message.error('请选择要删除的数据')
    return
  }
  let deleteId = pageData.addList.map((item: any) => item.itemId)
  let deleteIds = gridOption2.value.getSelectedRows().map((item: any) => item.itemId)
  let list = deleteId.filter((ids: any) => deleteIds.includes(ids))
  pageData.addList = pageData.addList.filter((item: any) => !list.includes(item.itemId))
}

//SOP内审检查项
const gridOption3 = ref()
const colState3 = ref()
const gridReady3 = (params: any) => {
  gridOption3.value = params.api
  colState3.value = params.columnApi
}
const tableColumns3: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  { headerName: '编号', field: 'id', width: 300 },
  { headerName: '检查内容', field: 'inspectContent', width: 310 },
  { headerName: '检查标准', field: 'inspectStandard', width: 310 },
  { headerName: '要求次数', field: 'inspectNumber', width: 300 },
  {
    headerName: '目标合格率',
    field: 'qualifiedRate',
    width: 310,
    cellRenderer: {
      template: `<span>{{ val.qualifiedRate + '%' }}</span>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '岗位', field: 'inspectType', width: 300 },
]

function PageSize3(val: any) {
  page.value = val
  QuerySOPchecks()
}
function change3(val: any) {
  size.value = val
  QuerySOPchecks()
}
//查询内容
function QuerySOPchecks() {
  post({
    url: '/qms/inspectionItem/pagedInspectionItems',
    data: {
      current: page.value,
      size: size.value,
      inspectContent: pageData.inspectContent,
    },
  }).then(({ data, code }: any) => {
    if (code === 200) {
      pageData.checkList = data.records
      gridOption3.value.setRowData(data.records)
      total.value = data.total
    }
  })
}

const handleOk = () => {
  if (gridOption3.value.getSelectedRows().length == 0) {
    Message.warning('请勾选数据!')
    return
  }
  let listArray: any = []
  listArray = listArray.concat(gridOption3.value.getSelectedRows())
  if (pageData.addList.length != 0) {
    let wlAarray: any = []
    for (let i = 0; i < listArray.length; i++) {
      wlAarray.push(listArray[i].id)
    }
    for (let i = 0; i < pageData.addList.length; i++) {
      if (wlAarray.includes(pageData.addList[i].itemId)) {
        Message.error(`不能重复选取编号为 ${pageData.addList[i].itemId} 的单据!`)
        return false
      }
    }
  }
  listArray.forEach((e: any) => {
    e['itemId'] = e['id']
    e['inspectContent'] = e['inspectContent']
    e['inspectNumber'] = e['inspectNumber']
    e['qualifiedRate'] = e['qualifiedRate']
    e['operatorPosition'] = e['inspectType']
    delete e.createTime
    delete e.createUser
    delete e.inspectType
    delete e.id
  })
  pageData.addList = [...pageData.addList, ...listArray]
  pageData.checkList = []
  pageData.inspectName = ''
  pageData.inspectContent = ''
  pageData.checkVisible = false
  return true
}

//检查名称
const changeName = () => {
  if (dataForm.planMonth != '' && dataForm.planPeriod != '') {
    const [year, planPeriod] = dataForm.planMonth.split('-')
    const formattedDate = `${year}年${parseInt(planPeriod)}月`
    dataForm.planName = formattedDate + dataForm.planPeriod
  } else {
    dataForm.planName = ''
  }
}

//员工
const getPerson = () => {
  post({
    url: '/qms/inspectionEmployee/listInspectionEmployees',
  }).then((res) => {
    if (res.code == 200) {
      pageData.operatorList = res.data
    } else {
      Message.error({
        content: res.message,
        duration: 5000,
      })
    }
  })
}

const personChange = (val: any) => {
  if (val.inspectorCodes.length !== 0) {
    val.inspectorNames = val.inspectorCodes.map((o1: any) => {
      const name = pageData.operatorList.find((o: any) => o1 === o.employeeCode)
      return name ? name.employeeName : ''
    })
  }
}

//检查明细
const checkDetail = (record: any) => {
  pageData.detialShow = true
  post({
    url: '/qms/inspectionPlanResult/listInspectionResults',
    data: {
      detailId: record.id,
      inspectNumber: record.inspectNumber,
    },
  }).then((res) => {
    if (res.code == 200) {
      pageData.statList = res.data.statList
      pageData.resultList = res.data.resultList
    } else {
      Message.error({
        content: res.message,
        duration: 5000,
      })
    }
  })
}

//结果审核 详情表单
const gridOption4 = ref()
const colState4 = ref()
const gridReady4 = (params: any) => {
  gridOption4.value = params.api
  colState4.value = params.columnApi
}
const tableColumns4: any = [
  { headerName: '编号', field: 'itemId', width: 195 },
  { headerName: '检查内容', field: 'inspectContent', width: 200 },
  { headerName: '要求次数', field: 'inspectNumber', width: 200 },
  {
    headerName: '已检次数',
    field: 'inspectNumber',
    width: 200,
    cellRenderer: (params: any) => {
      return '<span>' + (params.data.qualifiedCount + params.data.unqualifiedCount) + '</span>'
    },
  },
  {
    headerName: '已合格次数',
    field: 'qualifiedCount',
    width: 200,
    cellRenderer: {
      template: `<span>{{ val }}</span>`,
      setup(props: any) {
        let val = ref()
        val.value = props.params.data.qualifiedCount ? props.params.data.qualifiedCount : 0
        return {
          val,
        }
      },
    },
  },
  {
    headerName: '目标合格率',
    field: 'qualifiedRate',
    width: 200,
    cellRenderer: {
      template: `<span>{{ val.qualifiedRate + '%' }}</span>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  {
    headerName: '实际合格率',
    width: 200,
    cellRenderer: {
      template: `<span>{{ (val=== 'NaN' ? '0.0' : val) + '%' }}</span>`,
      setup(props: any) {
        let val = ref()
        let count = props.params.data.qualifiedCount + props.params.data.unqualifiedCount
        val.value = (
          (parseFloat(props.params.data.qualifiedCount) / parseFloat(count)) *
          100
        ).toFixed(1)
        return {
          val,
        }
      },
    },
  },
  {
    headerName: '检查结果',
    field: 'inspectResult',
    width: 200,
    cellRenderer: {
      template: `<span>{{ val.inspectResult }}</span>`,
      setup(props: any) {
        let val = ref(props.params.data)
        let count = props.params.data.qualifiedCount + props.params.data.unqualifiedCount
        let result = (
          (parseFloat(props.params.data.qualifiedCount) / parseFloat(count)) *
          100
        ).toFixed(4)
        if (result > props.params.data.qualifiedRate || result == props.params.data.qualifiedRate) {
          props.params.data.inspectResult = '合格'
        } else {
          props.params.data.inspectResult = '不合格'
        }

        return {
          val,
        }
      },
    },
  },
  { headerName: '岗位', field: 'operatorPosition', width: 200 },
  {
    headerName: '操作',
    field: 'action',
    width: 150,
    pinned: 'right',
    cellRenderer: {
      template: `<a-tag class="tagCss" @click="c">检查明细</a-tag>`,
      setup(props: any) {
        const c = () => {
          checkDetail(props.params.data)
        }
        return {
          c,
        }
      },
    },
  },
]

//汇总检查明细
const tableColumns5: any = [
  { headerName: '检查内容', field: 'itemContent', width: 200 },
  { headerName: '要求次数', field: 'inspectNumber', width: 200 },
  { headerName: '检查人', field: 'employeeName', width: 200 },
  { headerName: '要求次数', field: 'personalNumber', width: 200 },
  { headerName: '欠数', field: 'uncheckedTotalNumber', width: 200 },
  { headerName: '合格次数', field: 'qualifiedCount', width: 200 },
  { headerName: '不合格次数', field: 'unqualifiedCount', width: 200 },
]
//个人检查明细
const tableColumns6: any = [
  { headerName: '检查人员', field: 'employeeName', width: 200 },
  {
    headerName: '检查结果',
    field: 'isQualified',
    width: 200,
    cellRenderer: (params: any) => {
      let val = params.value == 0 ? '不合格' : '合格'
      return '<span>' + val + '</span>'
    },
  },
  { headerName: '检查时间', field: 'createTime', width: 200 },
  { headerName: '机台', field: 'machineCode', width: 200 },
  { headerName: '楼层', field: 'floorNum', width: 200 },
  { headerName: '被审员工', field: 'auditedEmployee', width: 200 },
  {
    headerName: '图片',
    field: 'resultImg',
    width: 200,
    cellRenderer: {
      template: `<a-image v-if="val.resultImg" :src="val.resultImg"/>
					   <span v-if="!val.resultImg">暂无图片</span>`,
      setup(props: any) {
        let val = ref(props.params.data)
        return {
          val,
        }
      },
    },
  },
  { headerName: '备注', field: 'remark', width: 200 },
]

//查询织造中心的数据
const getTreeCompany = () => {
  post({
    url: 'org/baCompany/getTreeCompanyOrDepartment',
    data: {},
  }).then(({ data, code }: any) => {
    if (code === 200) {
      pageData.planOperatorList = data[0].children.filter((o: any) => o.label == '织造中心')[0].children
      pageData.planOperatorList = pageData.planOperatorList.map((o: any) => {
        return { companyId: o.value,companyName: o.label }
      })
    } else {
      Message.error({
        content: '查询失败！',
        duration: 5000,
      })
    }
  })
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  doRefresh()
})
</script>
<style lang='less' scoped>
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag) {
  color: #4e5969 !important;
  background-color: white;
  border-color: white;
  font-size: 14px;
}
</style>